import React, { Component } from 'react'
import styles from './searchCenter.module.scss'
import { withRouter } from "react-router-dom"
import BrNav from "../brNav/BrNav"
import { SearchBar } from 'antd-mobile';
import { searchGoods } from "../../data/api"
class SearchCenter extends Component {
    timer = null;//类属性
    vaild = true;//标识
    state = {
        inputVal: '',//输入框输入的值
        productList: [],//搜索出来的列表
    }
    //防抖
    debounce = (fn, ms) => {
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = null;
        }
        this.timer = setTimeout(fn, ms);
    }
    throttle = (fn, ms) => {
        if (this.vaild) {
            this.vaild = false;
            setTimeout(() => {
                this.vaild = true;
                fn.call(this);
            }, ms)
        }
    }

    handleChange = (value) => {
        // console.log(value);
        this.throttle(async () => {
            let res = await searchGoods({
                query: value
            })
            console.log(res);
            this.setState({
                //如果res.message没有值时map会报错，没有值时给它一个空数组
                productList: res.message || []
            });
        }, 500)
    }


    render() {
        return (
            <div className={styles.searchContainner}>
                <BrNav title="搜索中心" left={true}></BrNav>
                <SearchBar placeholder="Search"
                    showCancelButton
                    cancelText="搜索"
                    // value={this.state.inputVal}
                    onChange={this.handleChange} />
                <div className={styles.searchContent}>
                    <div className={styles.goodsList}>
                        {
                            this.state.productList.map((v, i) => {
                                return <div className={styles.goodItem} key={v.goods_id} onClick={() => {
                                    this.props.history.push('/goodDetail/' + v.goods_id);
                                }}>
                                    <span className={styles.message}>{v.goods_name}</span>
                                </div>
                            })
                        }
                    </div>
                </div>
            </div>
        )
    }
}
export default withRouter(SearchCenter)